import router from "./router";
import store from "./store";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { Message } from "element-ui";
import { getToken } from "./utils/auto.js";

import Layout from "@/layout"; // 主页

import morkRouterList from "@/mock/router"; //路由数据

NProgress.configure({
  showSpinner: false,
}); // NProgress不显示小图标

// 白名单
const wList = ["login", "NotFound"];

// 前置拦截
router.beforeEach(async (to, from, next) => {
  NProgress.start(); // 启动加载条

  const token = getToken(); // 获取令牌s
  // 判断是否有令牌
  if (!wList.includes(to.name) && !token) {
    Message({
      showClose: true,
      message: "您还未登入！",
      type: "error",
    });
    next(`/login?redirect=${to.path}`); // 重定向至登录页
    NProgress.done();
  } else if (token) {
    if (to.path === "/login") {
      //如果已经登入，重定向到主页
      next({
        path: "/",
      });
      NProgress.done();
    }
    try {
      const hasGetUserInfo = store.getters.name;
      //确定用户是否通过getInfo获取权限角色
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          // 获取用户数据
          await store.dispatch("admin/getInfo");
          // 拼接菜单

          // 获取mork数据
          let myRoutes = myFilterAsyncRoutes(morkRouterList);
          myRoutes.push({
            path: "/*",
            redirect: "/404",
            hidden: true,
          });
          // 动态添加路由数据
          for (let i = 0; i < myRoutes.length; i++) {
            router.addRoute(myRoutes[i]);
          }
          next({
            ...to,
            replace: true,
          });
          // 错误时
        } catch (error) {
          // 干掉令牌
          await store.dispatch("admin/resetToken");
          Message.error(error || "Has Error");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    } catch (error) {
      await store.dispatch("admin/resetToken");
      next({
        name: "login",
      });
      NProgress.done();
    }
  } else {
    next();
  }
});

router.afterEach((to) => {
  // 判断目前点击的页面是否在存储之中
  let visitedRoutes = store.getters.visitedRoutes;
  let result = visitedRoutes.find((val) => val.name == to.name);
  // 如果不在
  if (!result && !wList.includes(to.name)) {
    let intrusiveRouter = {
      name: to.name,
      path: to.path,
      title: to.meta.title,
    };
    visitedRoutes.push(intrusiveRouter);
    store.dispatch("app/updateRoutes", visitedRoutes);
  }
  NProgress.done();
});

// 递归菜单处理
function myFilterAsyncRoutes(menuList) {
  let menuRouter = [];
  menuList.forEach((menu) => {
    let routerInfo = {
      path: menu.path,
      name: menu.name,
      meta: menu.meta,
      component:
        menu.component === "Layout"
          ? Layout
          : () => import(`@/views/${menu.component}.vue`),
    };
    if (menu.redirect) {
      routerInfo.redirect = menu.redirect;
    }
    if (menu.children && menu.children.length) {
      routerInfo.children = myFilterAsyncRoutes(menu.children);
    }
    menuRouter.push(routerInfo);
  });
  return menuRouter;
}
